const express = require('express');
const { Server } = require("socket.io");
const { createServer } = require("https");
const fs = require('fs');
// const ws = require('ws');

// const wss = new ws.Server({
//     port: 3000
// })


// wss.on('connection', function (ws) {
//     console.log('A new client connected');
//     ws.on('message', function (message) {
//         console.log(`Client has sent us: ${message}`);
//       // 广播消息到所有客户端
//       wss.clients.forEach(function each(client) {
//         client.send(1);
//       });
//     })
// });
const app = express();
const options = {
    key: fs.readFileSync('./CA/server.key'),
    cert: fs.readFileSync('./CA/server.cert')
}
const httpServer = createServer(options,app);


//解决跨域
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  next();
});

app.get('/', (req, res) => {
  res.send('Hello World!')
})


const io = new Server(httpServer,{ cors: { origin: "*" } });

io.on("connection", (socket) => {
    console.log('有一个用户连接成功')
    socket.emit('createroom', {room:`${socket.id}`,user_id:socket.id})
    socket.on('msg', (msg) => {
      console.log('接收到消息：', msg)
      // 广播消息到所有客户端
      socket.emit('msg', msg);
    })
    socket.on('sendtextmsg', (data) => {
        const res = JSON.parse(data)
        console.log('接收到消息：', res.text)
        socket.to(res.sendID).emit('receptiontextmsg', {name:socket.id,text:res.text})
    })

    //视频聊天
    socket.on('sendcall', (data) => {
        const res = JSON.parse(data)
        socket.to(res.sendtoID).emit('sendcallmsg', data)
    })

    socket.on('answer_ice',(data)=>{
        const { user_id } = JSON.parse(data)
        console.log('answer_ice',user_id)
        socket.to(user_id).emit('answer_ice_msg', data)
    })

    socket.on('offer_ice',(data)=>{
        const { user_id } = JSON.parse(data)
        console.log('offer_ice',user_id)

        socket.to(user_id).emit('offer_ice_msg', data)
    })

    
    // 监听连接断开事件（刷新页面可测试）
    socket.on('disconnect', () => {
      console.log('用户已断开连接')
    })
});

// app.listen(3000, () => {
//     console.log("Server is running on port 3000");
// });

httpServer.listen(3000, () => {
    console.log("Server is running on port 3000");
});